<template>
  <div>
    <h1>{{id?'编辑':'新建'}}广告位 </h1>
    <el-form @submit.native.prevent="save" label-width="140px" label-position="right">
      <el-form-item label="名称" >
        <el-input v-model="model.name" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="广告">
        <el-button size="small" @click="model.items.push({})"><i class="el-icon-plus"></i>添加广告</el-button>
          <el-row type="flex" style="flex-wrap:wrap">
            <el-col :span="24" v-for="(item,index) in model.items" :key="index">
              <el-form-item label="跳转链接（URL）">
                <el-input placeholder="" v-model="item.url"></el-input>
              </el-form-item>
              <el-form-item label="图片" style="margin-top:0.5rem">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :headers="getAuthorization()"
                  :on-success="res => $set(item, 'image', res.url)">
                  <img v-if="item.image" :src="item.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item >
                <el-button type="danger" @click="model.skills.splice(index,1)">删除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      model: {
        name: '',
        items: []
      }
    }
  },
  props: {
    id: {}
  },
  methods: {
    // 点击按钮提交
    async save () {
      let res
      if (this.id) {
        // 编辑提交
        res = await this.$http.put(`rest/ads/${this.id}`, this.model)
      } else {
        // 新增提交
        res = await this.$http.post('rest/ads', this.model)
      }
      console.log(res)
      // 注意这里是前端页面路径，不需要加rest
      this.$router.push('/ads/list')
      this.$message.success('保存成功')
    },
    // 根据id获取编辑分类的信息
    async fetch () {
      const res = await this.$http.get(`rest/ads/${this.id}`)
      this.model = Object.assign({}, this.model, res.data)
      // this.model = res.data
    }
  },
  created () {
    this.id && this.fetch()
  }
}
</script>
